package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.constant.XcPlusConstant;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.utils.DateUtil;
import com.xuecheng.base.utils.MD5Util;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.vo.UploadFileResultVo;
import com.xuecheng.media.service.MediaFileService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/9/10 8:58
 */
@Service
@Slf4j
public class MediaFileServiceImpl extends ServiceImpl<MediaFilesMapper,MediaFiles> implements MediaFileService {

    @Autowired
    MediaFilesMapper mediaFilesMapper;

    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucket.files}")
    private String bucketName;

    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    /**
     * 上传图片接口
     * @param filedata
     * @return
     */
    @Override
    public UploadFileResultVo upload(MultipartFile filedata) {

        String dateStr = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
        log.info("日期格式化:{}",dateStr);

        try {
            //这里的md5值应该指的是文件的md5，不是文件名的md5？？？
            String md5Str = DigestUtils.md5DigestAsHex(filedata.getInputStream());
            log.info("md5Str:{}",md5Str);

            //获取文件后缀名
            String originalFilename = filedata.getOriginalFilename();
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            //bucket中的对象名
            String objectName = dateStr + "/" + md5Str + suffix;

            //构建PutObjectArgs对象
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(filedata.getInputStream(),
                            filedata.getInputStream().available(), -1).build();
            //上传文件
            minioClient.putObject(putObjectArgs);
            //程序能到这里，说明文件上传成功
            //文件相关信息存入数据库

            MediaFiles mediaFiles = new MediaFiles();
            mediaFiles.setFileId(md5Str);
            mediaFiles.setId(md5Str);
            mediaFiles.setCompanyId(1232141425L);
            mediaFiles.setAuditStatus(XcPlusConstant.OBJECT_AUDIT_STATUS_UNAUDITED);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setFileSize(filedata.getSize());//文件大小
            mediaFiles.setUrl("/" + bucketName + "/" + objectName);
            mediaFiles.setUsername("91先生");
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setFileType(XcPlusConstant.FILE_TYPE_IMAGE);
            mediaFiles.setFilename(originalFilename);//原文件的文件名
            mediaFiles.setStatus("1");
            mediaFiles.setBucket(bucketName);

            //插入
            boolean save = save(mediaFiles);
            if (!save){
                throw new XueChengPlusException("添加media图片数据失败");
            }
            UploadFileResultVo uploadFileResultVo = new UploadFileResultVo();
            BeanUtils.copyProperties(mediaFiles,uploadFileResultVo);

            return uploadFileResultVo;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
